import React, { Component, useState } from 'react'
import axios from 'axios'
import { UploadOutlined } from '@ant-design/icons'
import type { UploadProps } from 'antd'
import { Button, message, Upload } from 'antd'
/**
 *
 */
const UploadFile = () => {
  const [imgSrc, setImgSrc] = useState<string>('')
  const onChange = async (e: any) => {
    console.log('e:', e.target.files)
    // 上传图片一般识别两种数据类型 base64 newFileReader, formData
    const file = e.target.files[0]
    const formData = new FormData()
    formData.append('file', file)
    const data = await axios.post('http://localhost:3000/api/upload', formData)
    console.log('data:', data.data.url)
    setImgSrc(data.data.url)
  }

  const props: UploadProps = {
    name: 'file',
    action: 'http://localhost:3000/api/upload',
    headers: {
      authorization: 'authorization-text',
    },
    onChange(info) {
      console.log('info:', info)
      if (info.file.status !== 'uploading') {
        console.log(info.file.response.url, info.fileList)
        setImgSrc(info.file.response.url)
      }
      if (info.file.status === 'done') {
        message.success(`${info.file.name} file uploaded successfully`)
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} file upload failed.`)
      }
    },
  }
  return (
    <div>
      <input type="file" onChange={onChange}></input>
      <button onClick={() => {}}>上传</button>
      <img src={imgSrc} alt="" />

      <hr />
      {/* ui框架上传 */}
      <Upload {...props}>
        <Button icon={<UploadOutlined />}>Click to Upload</Button>
      </Upload>
    </div>
  )
}

export default UploadFile
